//
//  HomeTeachViewController.m
//  Edumap
//
//  Created by 刘建峰 on 16/7/18.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "HomeTeachViewController.h"
#import "HomeTeachCollectionViewCell.h"
#import "MessageCenterViewController.h"
#import "TutorListViewController.h"
#import "DrivateTutorDetailViewController.h"
#import "AdverDetailViewController.h"

static NSString * CellIdentifier = @"HomeTeachCollectionViewCell";

@interface HomeTeachViewController ()
<UICollectionViewDataSource,UICollectionViewDelegate,BestScrollViewDelegate,BestScrollViewDatasource,UIScrollViewDelegate,UITextFieldDelegate,CLLocationManagerDelegate,UIAlertViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property(nonatomic,strong)CLLocationManager * locationManger;

@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UILabel *regionLabel;

@property (strong, nonatomic) IBOutlet UIScrollView *scroview;
@property (strong, nonatomic) IBOutlet UICollectionView *collectView;
@property (strong, nonatomic) IBOutlet UILabel *BGLabel;
@property (strong, nonatomic) IBOutlet UITextField *textField;
@property (strong, nonatomic) IBOutlet UILabel *messageNumberLabel;
@property (nonatomic,strong)  BestScrollView *headerScroll;//滚动栏
@property (nonatomic,strong)  NSMutableArray  *imageArray;
@property (strong, nonatomic) NSMutableArray *collectionArray;
@property (strong, nonatomic) NSMutableArray *QueryAllPhasesArray;//阶段
@property (strong, nonatomic) NSMutableArray *subjectsArray;//科目
@property(nonatomic,assign)CGFloat offSet;

@end

@implementation HomeTeachViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
   
    
    if ([Common getLoginStatus]) {
        _messageNumberLabel.hidden = YES;
        [self getnoticeNum];
    } else {
        _messageNumberLabel.hidden = YES;
    }
    [self QueryAllPhases];
    [self subjects];
     _regionLabel.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"cityName"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _collectionArray = [NSMutableArray array];
    _imageArray = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
    [self getAdvertiseBanner];

}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroview];
    _scroview.frame = CGRectMake(0, 64*VerticalRatio(), 320*VerticalRatio(), 504*VerticalRatio());
    _scroview.contentSize = flexibleSize(CGSizeMake(0, 860), NO);
    _scroview.delegate = self;
    
    _collectView.frame = CGRectMake(0, 430*VerticalRatio(), 320*VerticalRatio(), CGRectGetHeight(_collectView.frame)-49);
    
    self.messageNumberLabel.layer.masksToBounds = YES;
    self.messageNumberLabel.layer.cornerRadius = 7*VerticalRatio();
    self.BGLabel.layer.masksToBounds = YES;
    self.BGLabel.layer.cornerRadius = 3*VerticalRatio();
    _textField.delegate = self;
    
    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    self.collectView.collectionViewLayout = flowLayout;
    self.collectView.userInteractionEnabled=YES;
    [self.collectView registerNib:[UINib nibWithNibName:CellIdentifier bundle:nil] forCellWithReuseIdentifier:CellIdentifier];
    self.collectView.dataSource = self;
    self.collectView.delegate = self;
    
    self.collectView.backgroundColor = [UIColor whiteColor];

    //广告栏
    _headerScroll=[[BestScrollView alloc]  initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 160), NO)];
    [self.scroview addSubview:_headerScroll];
    

}


#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.scroview.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.scroview.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self recommended];
        });
        
    }];
    // 马上进入刷新状态
    [self.scroview.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.collectionArray.count == _totle) {
        [self.collectView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self recommended];
        });
    }
    
}

#pragma mark - 获取精彩推荐
-(void)recommended{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"1" forKey:@"mstoIsRecommend"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_mallExpertRecommendList withHttpType:@"POST" withTag:JY_JY_mallExpertRecommendList];
}


#pragma mark - 重新定位
- (IBAction)reLocation:(id)sender {
    UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"" message:@"是否请求定位?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alertView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [self startLocation];
    }
}

#pragma mark - 消息
- (IBAction)message:(id)sender {
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return;
    }
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"TeachStoryboard" bundle:nil];
    MessageCenterViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"MessageCenter"];
    page.unReadNum = [_messageNumberLabel.text integerValue];
    [[Common getNavigation] pushViewController:page];
}


#pragma mark - 阶段
- (IBAction)level:(UIButton *)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeTeachStoryboard" bundle:nil];
    TutorListViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"TutorList"];
    page.leftArray = _QueryAllPhasesArray;
    page.rightArray = _subjectsArray;
    if (sender.tag == 10) {
        for (int i = 0; i < _QueryAllPhasesArray.count; i++) {
            NSString *mlagName = [NSString stringWithFormat:@"%@",_QueryAllPhasesArray[i][@"mlagName"]];
            NSLog(@"%@",mlagName);
            if ([mlagName isEqualToString:@"幼儿"]) {
                page.leftCount = i;
                page.rightCount = 0;
                [[Common getNavigation] pushViewController:page];
            }
        }
        
        
    } else if (sender.tag == 11) {
        for (int i = 0; i < _QueryAllPhasesArray.count; i++) {
            NSString *mlagName = [NSString stringWithFormat:@"%@",_QueryAllPhasesArray[i][@"mlagName"]];
            if ([mlagName isEqualToString:@"小学"]) {
                
                page.leftCount = i;
                page.rightCount = 0;
 
                [[Common getNavigation] pushViewController:page];
            }
        }
        
        
    } else if (sender.tag == 12) {
        for (int i = 0; i < _QueryAllPhasesArray.count; i++) {
            NSString *mlagName = [NSString stringWithFormat:@"%@",_QueryAllPhasesArray[i][@"mlagName"]];
            if ([mlagName isEqualToString:@"初中"]) {
                page.leftCount = i;
                page.rightCount = 0;
                [[Common getNavigation] pushViewController:page];
            }
        }
        
        
    } else if (sender.tag == 13) {
        for (int i = 0; i < _QueryAllPhasesArray.count; i++) {
            NSString *mlagName = [NSString stringWithFormat:@"%@",_QueryAllPhasesArray[i][@"mlagName"]];
            if ([mlagName isEqualToString:@"高中"]) {
                page.leftCount = i;
                page.rightCount = 0;
                [[Common getNavigation] pushViewController:page];
            }
        }
        
        
    }
    
}

#pragma mark - 课程
- (IBAction)subjects:(UIButton *)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeTeachStoryboard" bundle:nil];
    TutorListViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"TutorList"];
    page.leftArray = _QueryAllPhasesArray;
    page.rightArray = _subjectsArray;
    if (sender.tag == 1) {
        //语文
        for (int i = 0; i < _subjectsArray.count; i++) {
            NSString *mlagName = [NSString stringWithFormat:@"%@",_subjectsArray[i][@"mlsuName"]];
            if ([mlagName isEqualToString:@"语文"]) {
                page.leftCount = 0;
                page.rightCount = i;
                [[Common getNavigation] pushViewController:page];
            }
        }
        
    } else if (sender.tag == 2) {
        //数学
        for (int i = 0; i < _subjectsArray.count; i++) {
            NSString *mlagName = [NSString stringWithFormat:@"%@",_subjectsArray[i][@"mlsuName"]];
            if ([mlagName isEqualToString:@"数学"]) {
                page.leftCount = 0;
                page.rightCount = i;
                [[Common getNavigation] pushViewController:page];
            }
        }
        
    } else if (sender.tag == 3) {
        //英语
        for (int i = 0; i < _subjectsArray.count; i++) {
            NSString *mlagName = [NSString stringWithFormat:@"%@",_subjectsArray[i][@"mlsuName"]];
            if ([mlagName isEqualToString:@"英语"]) {
                page.leftCount = 0;
                page.rightCount = i;
                [[Common getNavigation] pushViewController:page];
            }
        }
        
    }
}

#pragma mark - 查询所有阶段
- (void)QueryAllPhases {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_mallLecturerAgeList withHttpType:@"POST" withTag:JY_JY_mallLecturerAgeList];
}

#pragma mark - 查询科目
- (void)subjects {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_mallLecturerSubjectList withHttpType:@"POST" withTag:JY_JY_mallLecturerSubjectList];
}

#pragma mark  获取首页广告BANNER--=========================================
-(void)getAdvertiseBanner{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"2" forKey:@"Id"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_queryAdvertismentById withHttpType:@"POST" withTag:JY_JY_queryAdvertismentById];
}


#pragma mark === 获取未读信息数量
- (void)getnoticeNum{
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msceMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_unreadInformation withHttpType:@"POST" withTag:JY_JY_unreadInformation];
}

#pragma mark ==== UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self hideKeyBoard];
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeTeachStoryboard" bundle:nil];
    TutorListViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"TutorList"];
    page.leftArray = _QueryAllPhasesArray;
    page.rightArray = _subjectsArray;
    page.searchStr = _textField.text;
    [[Common getNavigation] pushViewController:page];
    return YES;
}


#pragma mark -- coreLocation

- (void)startLocation{
    
    // 判断定位操作是否被允许
    
    if([CLLocationManager locationServicesEnabled]) {
        
        _locationManger = [[CLLocationManager alloc] init];
        _locationManger.delegate = self;
        _locationManger.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManger.distanceFilter = 5.0f;
        // 总是授权
        [_locationManger requestAlwaysAuthorization];
        if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8) {
            [_locationManger requestWhenInUseAuthorization];//使用程序其间允许访问位置数据（iOS8定位需要）
            [_locationManger requestAlwaysAuthorization];
        }
        [_locationManger startUpdatingLocation];
        
        
    }else {
        
        //提示用户无法进行定位操作
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"定位不成功 ,请确认开启定位" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        
        [alertView show];
        
    }
    // 开始定位
    [_locationManger startUpdatingLocation];
}


- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        for (CLPlacemark * placemark in placemarks) {
            
            NSDictionary *test = [placemark addressDictionary];
            //  Country(国家)  State(城市)  SubLocality(区)
            NSString * cityName = test[@"SubLocality"];
            _regionLabel.text = cityName;
            [[NSUserDefaults standardUserDefaults]setObject:cityName forKey:@"cityName"];
        }
    }];
    [_locationManger stopUpdatingLocation];
}


#pragma mark  ==== scroViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == _collectView || scrollView== _scroview) {
        _offSet = scrollView.contentOffset.y;
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (scrollView == _collectView || scrollView == _scroview ) {
        if (scrollView.contentOffset.y>_offSet) {
            
            [_scroview setContentOffset:CGPointMake(0, 405*VerticalRatio()) animated:YES];
            if(_collectView.contentSize.height>_collectView.frame.size.height){
                _scroview.scrollEnabled = NO;
            }
            _collectView.scrollEnabled = YES;
        }else{
            if (scrollView == _scroview) {
                [_scroview setContentOffset:CGPointMake(0, 0) animated:YES];
                _scroview.scrollEnabled = YES;
                _collectView.scrollEnabled = NO;
            }else{
                if (decelerate == YES) {
                    [_scroview setContentOffset:CGPointMake(0, 0) animated:YES];
                    _scroview.scrollEnabled = YES;
                    _collectView.scrollEnabled = NO;
                }
            }
            
        }
    }
}



#pragma  mark BestView Delegate Data=source=====================


- (NSInteger)numberOfPages
{
    
    return  self.imageArray.count;
    
}

- (UIView *)pageAtIndex:(NSInteger)index
{
    
    if (self.imageArray.count>0) {
        
        UIImageView  *imageView=[[UIImageView alloc]  initWithFrame: flexibleFrame(CGRectMake(0, 0, 320, 160), NO)];
        [imageView  sd_setImageWithURL:[NSURL URLWithString: [NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,_imageArray[index][@"titleimg"]]] placeholderImage:[UIImage imageNamed:@"school1"]];
        return imageView;
    }
    return nil;
}


- (void)didClickPage:(BestScrollView *)csView atIndex:(NSInteger)index
{
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"SchoolStoryboard" bundle:nil];
    AdverDetailViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"AdverDetail"];
 page.adverId = [NSString stringWithFormat:@"%@",_imageArray[index][@"id"]];
    [[Common getNavigation] pushViewController:page];
}


#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
 
        return self.collectionArray.count;

}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
        return CGSizeMake(159*VerticalRatio(), 175*VerticalRatio());

}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0,0, 0, 0);
    
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
   
        HomeTeachCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
        
    NSString *imageStr = [NSString stringWithFormat:@"%@",self.collectionArray[indexPath.row][@"mexpImage"]];
    if (imageStr && imageStr.length>0 && ![self.collectionArray[indexPath.row][@"mexpImage"] isEqual:[NSNull null]]) {
        [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,imageStr]]];
    }
    
    NSArray *mallLecturerAges = [NSArray array];
    mallLecturerAges = self.collectionArray[indexPath.row][@"mallLecturerAges"];
    NSString *mlagNames = @"";
    for (int i = 0; i < mallLecturerAges.count; i++) {
        NSString *mlagName = [NSString stringWithFormat:@"%@",mallLecturerAges[i][@"mlagName"]];
        mlagNames = [mlagName stringByAppendingString:mlagName];
    }
    
    NSString * titleStr = [NSString stringWithFormat:@"%@  ",self.collectionArray[indexPath.row][@"mexpName"]];
    NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@%@",titleStr,mlagNames]];

    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:11] range:NSMakeRange(titleStr.length, str.length-titleStr.length)];
    [cell.titleLabel setAttributedText:str];

    NSArray *mallLecturerSubjects = [NSArray array];
    mallLecturerSubjects = self.collectionArray[indexPath.row][@"mallLecturerSubjects"];
    NSString *mlsuNames = @"";
    for (int i = 0; i < mallLecturerSubjects.count; i++) {
        NSString *  mlsuName = [NSString stringWithFormat:@"%@",mallLecturerSubjects[i][@"mlsuName"]];
        mlsuNames = [mlsuNames stringByAppendingString:mlsuName];
    }
    
    cell.subjectsLabel.text = mlsuNames;
    cell.moneyLabel.text =  [NSString stringWithFormat:@"%@元/小时",self.collectionArray[indexPath.row][@"mexpPrice"]];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeTeachStoryboard" bundle:nil];
    DrivateTutorDetailViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"DrivateTutorDetail"];
    
    page.mexpId = self.collectionArray[indexPath.row][@"mexpId"];
    page.backBlock = ^(){};
    [[Common getNavigation] pushViewController:page];
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_scroview.header endRefreshing];
    [_collectView.footer endRefreshing];
    if (tag==JY_JY_mallLecturerAgeList) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            self.QueryAllPhasesArray = [NSMutableArray array];
            self.QueryAllPhasesArray = [database[@"result"]mutableCopy];
            NSDictionary *dic =@{@"mlagName":@"全部阶段"};
            [self.QueryAllPhasesArray insertObject:dic atIndex:0];
            
        }
    } else if (tag==JY_JY_mallLecturerSubjectList) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            self.subjectsArray = [NSMutableArray array];
            self.subjectsArray = [database[@"result"]mutableCopy];
            NSDictionary *dic =@{@"mlsuName":@"所有科目"};
            [self.subjectsArray insertObject:dic atIndex:0];
        }

    }else if (tag==JY_JY_unreadInformation) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            _messageNumberLabel.text = [NSString stringWithFormat:@"%@",database[@"result"][@"noReadNum"]];
            _messageNumberLabel.text = [NSString stringWithFormat:@"%@",database[@"result"][@"noReadNum"]];
            _messageNumberLabel.hidden = NO;
            if ([_messageNumberLabel.text isEqualToString:@"0"]) {
                _messageNumberLabel.hidden = YES;
            }
        }
        
    }else if (tag == JY_JY_queryAdvertismentById){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            self.imageArray = database[@"result"];
            
            if (_imageArray.count>0) {
                self.headerScroll.delegate=self;
                self.headerScroll.datasource=self;
                [self.headerScroll showImageArray:self.imageArray   withAnimation:YES];
            }
        }
    }else if (tag == JY_JY_mallExpertRecommendList){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
        
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
        
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.collectView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.collectView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.collectionArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.collectionArray addObject:entity];
                }
                [_collectView reloadData];
                
            });

        }
    }
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    [_scroview.header endRefreshing];
    [_collectView.footer endRefreshing];
    [self dismissWaitDialog];
    
    
}


@end
